package org.example.demo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.example.demo.model.GoodsInfo;

import javax.annotation.PostConstruct;
import java.math.BigInteger;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Random;
import java.lang.reflect.Field;
import java.util.Map;

/**
 * 数据初始化器
 * 在应用启动时，从区块链读取现有商品并生成历史时间戳
 */
@Component
public class DataInitializer {
    
    @Autowired
    private GoodsService goodsService;
    
    @Autowired
    private TransferTimeService transferTimeService;
    
    private Random random = new Random();
    
    /**
     * 在应用启动后初始化数据
     */
    @PostConstruct
    public void initializeData() {
        // 延迟2秒执行，确保其他服务已启动
        try {
            Thread.sleep(2000);
            System.out.println("开始初始化历史时间戳数据...");
            
            // 检查是否已有数据记录
            boolean hasExistingRecords = false;
            try {
                Field recordsField = transferTimeService.getClass().getDeclaredField("transferRecords");
                recordsField.setAccessible(true);
                Map<String, ?> records = (Map<String, ?>) recordsField.get(transferTimeService);
                hasExistingRecords = records != null && !records.isEmpty();
                System.out.println("系统中现有 " + (records != null ? records.size() : 0) + " 条记录");
            } catch (Exception e) {
                System.err.println("检查现有记录时出错: " + e.getMessage());
            }
            
            // 只有在没有记录的情况下才生成新记录
            if (!hasExistingRecords) {
                System.out.println("未找到现有时间戳记录，开始生成历史数据...");
                initializeHistoricalTransferTimes();
                System.out.println("历史时间戳数据初始化完成");
            } else {
                System.out.println("已找到现有时间戳记录，跳过初始化");
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } catch (Exception e) {
            System.err.println("初始化历史时间戳失败: " + e.getMessage());
        }
    }
    
    /**
     * 为已有的商品生成历史时间戳
     */
    private void initializeHistoricalTransferTimes() {
        // 假设最大商品ID为100，尝试获取所有可能的商品ID
        for (int i = 0; i < 100; i++) {
            try {
                BigInteger goodsId = BigInteger.valueOf(i);
                
                // 检查该ID的记录是否已存在
                if (transferTimeService.getTransferRecord(goodsId.toString()) != null) {
                    System.out.println("商品ID " + goodsId + " 的时间戳记录已存在，跳过");
                    continue;
                }
                
                // 尝试获取商品信息
                GoodsInfo goods = goodsService.getGoods(goodsId);
                
                if (goods != null && goods.getHistoryOwners() != null && !goods.getHistoryOwners().isEmpty()) {
                    System.out.println("为商品ID " + goodsId + " 生成历史时间戳");
                    
                    // 获取创建时间
                    long createTime = goods.getCreateTime() != null ? 
                        goods.getCreateTime().longValue() : 
                        Instant.now().minus(30, ChronoUnit.DAYS).getEpochSecond();
                    
                    // 获取历史所有者列表
                    List<String> historyOwners = goods.getHistoryOwners();
                    
                    // 首先创建记录
                    TransferTimeService.TransferRecord record = new TransferTimeService.TransferRecord(goodsId.toString());
                    
                    // 为每个所有者生成时间戳
                    long currentTime = createTime;
                    for (String owner : historyOwners) {
                        // 记录当前所有者和时间
                        record.addTransfer(owner, currentTime);
                        
                        // 下一次转移的时间间隔在1小时到7天之间随机
                        long nextInterval = random.nextInt(7 * 24 * 60 * 60) + 60 * 60;
                        currentTime += nextInterval;
                        
                        // 确保不超过当前时间
                        if (currentTime > Instant.now().getEpochSecond()) {
                            currentTime = Instant.now().getEpochSecond();
                        }
                    }
                    
                    // 保存记录
                    transferTimeService.saveTransferRecord(goodsId.toString(), record);
                }
            } catch (Exception e) {
                // 忽略找不到商品的错误，继续尝试下一个ID
                System.out.println("商品ID " + i + " 不存在或读取失败: " + e.getMessage());
            }
        }
    }
} 